package com.supermap.util.base;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.supermap.pisaclient.R;
import com.supermap.pisaclient.common.SplashActivity;
import com.supermap.util.activity.NoNetworkGuideActivity;
import com.supermap.util.util.DBHelper;
import com.supermap.util.util.FileUtil;
import com.supermap.util.util.ResourcesUtil;
import com.supermap.util.util.SharedPreferencesUtil;
import com.supermap.util.util.ToastUtil;
import com.supermap.util.view.ViewUtils;
import com.supermap.util.widget.SystemBarTintManager;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (C) 2017 北京超图软件股份有限公司 版权所有
 * <p>
 * 功能描述：所有activity的基类 作者：李会林
 * <p>
 * 修改人： 修改描述： 修改日期
 */
public abstract class BaseActivity extends FragmentActivity {
    private static List<Activity> mActvityList;
    private FrameLayout mBaseContent;
    private LinearLayout mProgressBar;
    private LinearLayout mFailedView;
    private View mHeadLayout;
    private TextView mTvTitle;
    // private FrameLayout mLeftView;
    private ImageView mLeftImage;
    private TextView mTvLeftText;
    private TextView mTvRefreshText;
    private TextView mTvFailedDes;
    protected ImageView mBtnRight;
    protected TextView mTvRight;
    private ImageView mIvMiddle;
    private boolean isCancelable = false;
    private List<String> mRequestList;
    private ProgressDialog mProgressDialog;
    private TextView mMsgText;
    protected FrameLayout mRightContent;
    protected FrameLayout mParentContent;
    protected LinearLayout mBaseLayout;
    private View mNetNotifyView;
    private boolean mShowNetDefault = true;
    private boolean mNetNotConnect = false;
    public static final String CAN_GET_TIME = "can_get_time";
    private SharedPreferencesUtil mSp;
    private ImageView mFailedImage;
    private TextView mFailedBigDes;
    private boolean mPagePause = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        // 程序后台被杀再打开时登录信息丢失，这里去恢复一下
        /*if (!(this instanceof GuidActivity) && SystemConsts.mLoginInfo == null) {
            LoginBusiness.parseUserInfo(BaseActivity.this);
        }*/
        setStatusBarBg();
        mSp = SharedPreferencesUtil.getInstance(getApplicationContext());
        mRequestList = new ArrayList<String>();
        mBaseLayout = (LinearLayout) findViewById(R.id.base_layout);
        mBaseContent = (FrameLayout) findViewById(R.id.base_content);
        mRightContent = (FrameLayout) findViewById(R.id.right_content);
        mParentContent = (FrameLayout) findViewById(R.id.parent_content);
        mProgressBar = (LinearLayout) findViewById(R.id.base_progress);
        mProgressBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mFailedView = (LinearLayout) findViewById(R.id.base_failed);
        mFailedView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        mHeadLayout = findViewById(R.id.head);
        mTvTitle = (TextView) findViewById(R.id.middle_view);
        mLeftImage = (ImageView) findViewById(R.id.left_image);
        // mLeftView = (FrameLayout) findViewById(R.id.left_view);
        mTvLeftText = (TextView) findViewById(R.id.left_text);
        mBtnRight = (ImageView) findViewById(R.id.right_image);
        mTvRight = (TextView) findViewById(R.id.right_view);
        mIvMiddle = (ImageView) findViewById(R.id.middle_image);
        mMsgText = (TextView) findViewById(R.id.select_top);
        mTvRefreshText = (TextView) findViewById(R.id.failed_reflesh);
        mTvFailedDes = (TextView) findViewById(R.id.failed_des);
        mFailedImage = (ImageView) findViewById(R.id.base_load_failed_image);
        mFailedBigDes = (TextView) findViewById(R.id.failed_data_failed);
        // if (!DevicesUtil.isMX3) {
        // FragmentManager fragmentMrg = getSupportFragmentManager();
        // // 被杀掉后重新返回时可能有先前的fragment，这里全部移除
        // List<Fragment> fragments = fragmentMrg.getFragments();
        // try {
        // if (fragments != null && fragments.size() > 0) {
        // fragmentMrg.popBackStackImmediate();
        // FragmentTransaction transaction = fragmentMrg
        // .beginTransaction();
        // for (Fragment f : fragments) {
        // transaction.remove(f);
        // }
        // transaction.commit();
        //
        // fragmentMrg.executePendingTransactions();
        // }
        // } catch (Exception e) {
        //
        // }
        // }
        // setBackground(mBaseLayout);
        addViewIntoContent();
        if (mActvityList == null) {
            mActvityList = new ArrayList<Activity>();
        }
        mActvityList.add(this);
    }

    /**
     * 此方法必须在子类onCreate的时候调用
     */
    public abstract void addViewIntoContent();

    public FrameLayout getBaseContent() {
        return mBaseContent;
    }

    /**
     * 添加布局到容器
     *
     * @param layoutId
     */
    public View addView(int layoutId) {
        if (layoutId > 0) {
            mBaseContent.removeAllViews();
            View view = getLayoutInflater().inflate(layoutId, mBaseContent);
            ViewUtils.injectChildAndSelf(this);
            return view;
        } else {
            try {
                throw new Exception("layout ID can not be 0");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    /**
     * 设置添加view的容器背景色
     *
     * @param color
     */
    protected void setContentBackground(int color) {
        if (color > 0) {
            mBaseContent.setBackgroundColor(color);
        }
    }

    protected final void needHeader(boolean isNeed) {
        if (isNeed) {
            mHeadLayout.setVisibility(View.VISIBLE);
        } else {
            mHeadLayout.setVisibility(View.GONE);
        }
    }

    public static Activity getActivity(Class<?> cls) {
        if (mActvityList != null) {
            for (Activity act : mActvityList) {
                if (act.getClass() == cls) {
                    if (!act.isFinishing()) {
                        return act;
                    }
                }
            }
        }
        return null;
    }

    public static void finishExceptActivity(Class<?> cls) {
        if (mActvityList != null) {
            List<Activity> activityList = new ArrayList<Activity>();
            for (Activity act : mActvityList) {
                if (act.getClass() != cls) {
                    if (!act.isFinishing()) {
                        act.finish();
                    }
                } else {
                    activityList.add(act);
                }
            }
            mActvityList = activityList;
        }
    }

    /**
     * 关闭某个类型的activity
     */
    public void closeActivity(Class<?> cls) {
        if (mActvityList != null) {
            List<Activity> activityList = new ArrayList<Activity>();
            for (Activity act : mActvityList) {
                if (act.getClass() == cls) {
                    if (!act.isFinishing()) {
                        act.finish();
                    }
                } else {
                    activityList.add(act);
                }
            }
            mActvityList = activityList;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //这里要取消所有的请求
        mRequestList.clear();
        if (mActvityList != null) {
            mActvityList.remove(this);
        }
    }

    public final void addRequestKey(String key) {
        mRequestList.add(key);
    }


    public static void clearExit() {
        for (int i = 0; i < mActvityList.size(); i++) {
            Activity temp = mActvityList.get(i);
            if (!temp.isFinishing()) {
                temp.finish();
            }
        }
    }

    // 当前是否还有Activity存在
    public static boolean hasActivityExist() {
        if (mActvityList != null && mActvityList.size() > 0) {
            return true;
        }
        return false;
    }

    public final void showProgress(String handlerId, boolean cancelable) {
        if (handlerId == null) {
            return;
        }

        mRequestList.add(handlerId);
        isCancelable = cancelable;
        mFailedView.setVisibility(View.GONE);
        mProgressBar.getBackground().setAlpha(100);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    public final void showProgress() {
        mFailedView.setVisibility(View.GONE);
        mProgressBar.getBackground().setAlpha(100);
        mProgressBar.setVisibility(View.VISIBLE);
    }

    public final void closeProgress() {
        isCancelable = false;
        mProgressBar.setVisibility(View.GONE);
        mFailedView.setVisibility(View.GONE);
    }

    public final void showFailedView(String errorMsg) {
        isCancelable = false;
        mProgressBar.setVisibility(View.GONE);
        mFailedView.setVisibility(View.VISIBLE);
        mTvRefreshText.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(errorMsg)) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTvFailedDes
                    .getLayoutParams();
            lp.leftMargin = 0;
            mTvFailedDes.setLayoutParams(lp);
            mTvFailedDes.setText(errorMsg);
        }
    }

    public final void showFailedView(View.OnClickListener listener) {
        isCancelable = false;
        mProgressBar.setVisibility(View.GONE);
        mFailedView.setVisibility(View.VISIBLE);
        mTvRefreshText.setOnClickListener(listener);
    }

    public final void showFailedView(int imageId, String errorMsg) {
        isCancelable = false;
        mProgressBar.setVisibility(View.GONE);
        mFailedView.setVisibility(View.VISIBLE);
        mTvRefreshText.setVisibility(View.GONE);
        mFailedBigDes.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(errorMsg)) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mTvFailedDes
                    .getLayoutParams();
            lp.leftMargin = 0;
            mTvFailedDes.setLayoutParams(lp);
            mTvFailedDes.setGravity(Gravity.CENTER);
            mTvFailedDes.setText(errorMsg);
        }
        if (imageId > 0) {
            mFailedImage.setImageResource(imageId);
        }
    }

    @Override
    public final void setTitle(int res) {
        if (res > 0 && getResources().getText(res) != null) {
            mTvTitle.setText(res);
            mTvTitle.setVisibility(View.VISIBLE);
            mIvMiddle.setVisibility(View.INVISIBLE);
        } else {
            mTvTitle.setVisibility(View.INVISIBLE);
        }
    }

    public final void setTitle(String title) {
        if (!TextUtils.isEmpty(title)) {
            mTvTitle.setText(title);
            mTvTitle.setVisibility(View.VISIBLE);
            mIvMiddle.setVisibility(View.INVISIBLE);
        } else {
            mTvTitle.setVisibility(View.INVISIBLE);
        }
    }

    public final void setImageTitle(int drawable) {
        if (drawable > 0 && getResources().getDrawable(drawable) != null) {
            mIvMiddle.setImageResource(drawable);
            mIvMiddle.setVisibility(View.VISIBLE);
            mTvTitle.setVisibility(View.INVISIBLE);
        } else {
            mIvMiddle.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 设置标题点击事件
     *
     * @param listener
     */
    public final void setOnTitleClickListener(final View.OnClickListener listener) {
        if (listener != null) {
            mTvTitle.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    listener.onClick(v);
                }
            });
        } else {
            mTvTitle.setClickable(false);
        }
    }

    public final void setLeftVisibility(int visibility) {
        mLeftImage.setVisibility(visibility);
    }

    public final void setRightVisibility(int visibility) {
        mRightContent.setVisibility(visibility);
    }

    public final void setRightTxt(int res) {
        if (res > 0 && getResources().getText(res) != null) {
            mTvRight.setText(res);
            mTvRight.setVisibility(View.VISIBLE);
        } else {
            mTvRight.setVisibility(View.INVISIBLE);
        }
    }

    public final void setRightTxtEnable(boolean enable) {
        if (mTvRight != null) {
            mTvRight.setEnabled(enable);
            if (enable) {
                mTvRight.setTextColor(ResourcesUtil
                        .getColor(R.color.white));
            } else {
                mTvRight.setTextColor(ResourcesUtil
                        .getColor(R.color.common_black));
            }
        }
    }

    public final void setLeftDrawable(int resId) {
        mTvLeftText.setVisibility(View.GONE);
        mLeftImage.setImageResource(resId);
        mLeftImage.setVisibility(View.VISIBLE);
    }

    public final void setLeftText(int resId) {
        if (resId != 0) {
            mLeftImage.setVisibility(View.GONE);
            mTvLeftText.setText(resId);
            mTvLeftText.setVisibility(View.VISIBLE);
        }
    }

    public final void setRightDrawable(int resId) {
        mBtnRight.setImageResource(resId);
        mBtnRight.setVisibility(View.VISIBLE);
        mTvRight.setVisibility(View.GONE);
    }

    public final void setRightDrawableVisible(boolean enable) {
        if (enable) {
            mBtnRight.setVisibility(View.VISIBLE);
        } else {
            mBtnRight.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isCancelable && keyCode == KeyEvent.KEYCODE_BACK) {
            isCancelable = false;
            closeProgress();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 取消加载对话框
     */
    public final void closeProgressDialog() {
        isCancelable = false;
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public final void setBaseBg(int color) {
        if (mBaseLayout != null) {
            mBaseLayout.setBackgroundColor(color);
        }
    }

    public final void notifyNetworkInfo() {
        View child = mBaseLayout.getChildAt(1);
        if (mBaseLayout != null && (child == null || child != mNetNotifyView)) {
            mNetNotifyView = new HeaderNotifyView(this).getView();
            mBaseLayout.addView(mNetNotifyView, 1);
            mNetNotifyView.setClickable(true);
            mNetNotifyView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(BaseActivity.this,
                            NoNetworkGuideActivity.class);
                    startActivity(intent);

                }
            });
        }
    }

    public final void removeNetworkInfo() {
        View child = mBaseLayout.getChildAt(1);
        if (mBaseLayout != null && child != null && child == mNetNotifyView) {
            mBaseLayout.removeView(mNetNotifyView);
        }
    }

    public final int getHeadHeight() {
        return mHeadLayout.getHeight();
    }

    /**
     * 设置是否按默认显示网络状况 现在有两种 true 为默认 false 为不默认
     *
     * @param flag
     */
    public void setShowNetDefault(boolean flag) {
        mShowNetDefault = flag;
    }

    private void registerNetReceviver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetReceviver, filter);
    }

    private BroadcastReceiver mNetReceviver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if (info != null && info.isAvailable()) {
                if (mNetNotConnect) {
                    mNetNotConnect = false;
                    int type = info.getType();
                    if (type == ConnectivityManager.TYPE_WIFI) {
                        ToastUtil.showCustomViewToast(BaseActivity.this,
                                R.drawable.toast_wifi, R.string.toast_net_wifi,
                                Toast.LENGTH_SHORT);
                    } else {
                        ToastUtil.showCustomViewToast(BaseActivity.this,
                                R.drawable.toast_2g, R.string.toast_net_2g,
                                Toast.LENGTH_SHORT);
                    }
                }
                removeNetworkInfo();
            } else {
                mNetNotConnect = true;
                if (mShowNetDefault) {
                    ToastUtil.showCustomViewToast(BaseActivity.this,
                            R.drawable.toast_no_network, R.string.toast_no_net,
                            Toast.LENGTH_SHORT);
                } else {
                    notifyNetworkInfo();
                }
            }
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mNetReceviver);
        mPagePause = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerNetReceviver();
        mPagePause = false;
    }

    /**
     * 清除数据库缓存数据、SD卡缓存数据、接口缓存数据
     */
    protected void clearAllCache() {
        new AsyncTask<Context, Integer, Boolean>() {
            @Override
            protected Boolean doInBackground(Context... params) {
                DBHelper.clearAllTable(params[0]);
                FileUtil.deleteFiles(FileUtil.getDataCachePath());
                FileUtil.deleteFiles(getCacheDir().getAbsolutePath());
                FileUtil.deleteShareSdkData(params[0]);
                return true;
            }
        }.execute(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public boolean isAppOnForeground() {
        // Returns a list of application processes that are running on the
        // device
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    private void setStatusBarBg() {
        if (Build.VERSION.SDK_INT < 19) {// Build.VERSION_CODES.KITKAT
            return;
        }
        // 跳过不需要设置StatusBar样式的Activity界面
        Class<?> cls = getClass();
        if (cls == SplashActivity.class) {
            return;
        }
        setTranslucentStatusBar(true);
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setNavigationBarTintEnabled(true);
        tintManager.setTintColor(getResources()
                .getColor(R.color.common_title));
    }

    @TargetApi(19)
    private void setTranslucentStatusBar(boolean on) {
        Window window = getWindow();
        WindowManager.LayoutParams winParams = window.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        window.setAttributes(winParams);
    }

    private void setBackground(View root) {
        if (!needSetActivityBackground()) {
            return;
        }

        if (root != null) {
            root.setBackgroundColor(ResourcesUtil.getColor(R.color.common_grey_bg_color));
        }
    }

    protected boolean needSetActivityBackground() {
        return true;
    }
}
